#include <53func.h>
void A(){
    printf("Before A\n");
    sleep(3);
    printf("After A\n");
}
void B(){
    printf("Before B\n");
    sleep(3);
    printf("After B\n");
}
void C(){
    printf("Before C\n");
    sleep(3);
    printf("After C\n");
}
typedef struct shareRes_s {
    int flag; // 0 -- > A 未完成
    // 1 -- > A完成了，B未完成
    // 2 -- > B完成了
    pthread_mutex_t mutex;
    pthread_cond_t cond;
} shareRes_t;
void * threadFunc(void *arg){
    shareRes_t * pShareRes = (shareRes_t *)arg;
    pthread_mutex_lock(&pShareRes->mutex);
    if(pShareRes->flag == 0){
        pthread_cond_wait(&pShareRes->cond, &pShareRes->mutex);
    }
    pthread_mutex_unlock(&pShareRes->mutex);

    B();

    pthread_mutex_lock(&pShareRes->mutex);
    pShareRes->flag = 2;
    pthread_cond_signal(&pShareRes->cond);
    pthread_mutex_unlock(&pShareRes->mutex);

    pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
    shareRes_t shareRes;
    shareRes.flag = 0;
    pthread_mutex_init(&shareRes.mutex,NULL);
    pthread_cond_init(&shareRes.cond,NULL);

    pthread_t tid;
    pthread_create(&tid,NULL,threadFunc,&shareRes);
    
    // A C
    A();
    pthread_mutex_lock(&shareRes.mutex);
    shareRes.flag = 1;
    pthread_cond_signal(&shareRes.cond);
    pthread_mutex_unlock(&shareRes.mutex);
    
    pthread_mutex_lock(&shareRes.mutex);
    if(shareRes.flag == 1){
        pthread_cond_wait(&shareRes.cond, &shareRes.mutex);
    }
    pthread_mutex_unlock(&shareRes.mutex);
    C();

    pthread_join(tid,NULL);
    return 0;
}

